#define _GNU_SOURCE
#include "daemon_process.h"
#include <signal.h>
#include <stdbool.h>
#include "daemon_sub_process_monitor.h"
#include <stdlib.h>


sub_process_monitor_t *sub_process_monitor[2];

static bool is_running=true;

static void  signal_handler(int sig)
{
    is_running=false;
}


/**
 * @brief 守护进程启动
 */
int daemon_process_start(void)
{
    //1 配置  结束信号的接收
    signal(SIGINT, signal_handler );
    signal(SIGTERM, signal_handler );


    //2 初始化子进程的监控器 2 app ota 
   sub_process_monitor[0]= daemon_sub_process_monitor_init("app");
   sub_process_monitor[1]= daemon_sub_process_monitor_init("ota");


    //3 死循环  持续周期性监控子进程 

    while(is_running)
    {
        //3.1 循环检查子进程
        for(int i=0;i<2;i++)
        {
            daemon_sub_process_monitor_checkAndStart(sub_process_monitor[i]);
        }
        //3.2 间隔
        sleep(1);
    }


    //4  销毁杀死子进程
    for(int i=0;i<2;i++)
    {
        kill(sub_process_monitor[i]->sub_process_pid,SIGTERM );
        free(sub_process_monitor[i]);
    }
    return 0;

}